package mvc.core;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import mvc.core.log.Logger;

/**
 * 应用程序入口
 * 
 * @author liuzy
 * @version 2015年5月15日
 */
public class LauncherFilter implements Filter {
	
	private Logger logger = Logger.getLogger(LauncherFilter.class);
	
	private static BeanFactory factory = BeanFactory.getInstance();

	@Override
	public void init(FilterConfig config) throws ServletException {
		logger.debug("服务初始化...");
		factory.load();
		factory.ioc();
		logger.debug("服务初始化完成");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		request.setCharacterEncoding("UTF-8");
		String target = request.getRequestURI();
		logger.debug("收到原始请求:" + target);
		ActionMapping actionMapping = factory.getActionMapping(target);
		if (actionMapping != null) {
			logger.debug("请求有效,开始处理:");
			try {
				Object action = factory.getBean(actionMapping.getActionClass());
				Object result = actionMapping.getMethod().invoke(action);
				response.setContentType("json");
				PrintWriter pw = response.getWriter();
				pw.write(JSON.toJSONString(result));
				pw.flush();
				pw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			logger.debug("处理完成");
		} else {
			logger.debug("无映射,请求无效");
		}
	}

	@Override
	public void destroy() {
		factory.destroy();
	}

}
